﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Microsoft.DPE.UK.TFS.EmbeddedWorkItems.Common
{
    /// <summary>
    /// This class contains any logic that could be shared between different projects in the solution. In this case the server side event handler project and the client side
    /// check-in policy both need the same method, and it makes sense to share the same code.
    /// </summary>
    public class Logic
    {
        /// <summary>
        /// Returns any work items found in the supplied string.
        /// </summary>
        /// <param name="theComment">The string in which work items are located</param>
        /// <returns>An array of the work item ids, as ints</returns>
        public static int[] getWorkItemIds(string theComment)
        {
            const char START_MARKER = '[';
            const char END_MARKER = ']';

            var subStrings = theComment.Split(new char[] {START_MARKER}); 
            var workItems = new List<int>(); 
            
            foreach (var item in subStrings) 
            { 
                // Want to find a number bounded by the closing marker so as not to pick up an unintended work item
                // e.g. Closed 23 bugs including [123], don't want 23 to get picked out
                if (item.Contains(END_MARKER)) 
                {
                    // Find the position of the end marker
                    int endMarkerIndex = item.IndexOf(END_MARKER);
                    // Take the substring from the begging to the end marker
                    string wiID = item.Substring(0, endMarkerIndex);
                    // Remove any whitespaces etc
                    wiID = wiID.Trim();
                    try
                    {
                        workItems.Add(Convert.ToInt32(wiID));
                    }
                    catch (FormatException)
                    {
                        // Swallow exception - it wasn't a number, therefore not a work item id
                    }
                    catch (OverflowException)
                    {
                        // Swallow exception - the number was too large to accept
                    }
                     
                }
            }

            return workItems.ToArray();          
        }
    }
}
